<?php

namespace app\admin\model\xiluedu;

use think\Model;


class CourseCode extends Model
{

    

    

    // 表名
    protected $name = 'xiluedu_course_code';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'use_status_text',
        'usetime_text'
    ];
    const STRING = '012346789ABCDEFGHIJKLMNPQRSTUVWXYZ';

    
    public function getUseStatusList()
    {
        return ['0' => __('Use_status 0'), '1' => __('Use_status 1')];
    }


    public function getUseStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['use_status']) ? $data['use_status'] : '');
        $list = $this->getUseStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getUsetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['usetime']) ? $data['usetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setUsetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function course(){
        return $this->belongsTo("Course",'course_id','id',[],'INNER')->setEagerlyType(0);
    }

    public function user(){
        return $this->belongsTo("\app\admin\model\User",'user_id','id',[],'LEFT')->setEagerlyType(0);
    }

    public static function getCodes($course_id,$num=100,$length=6){
        $array = [];
        for($i=0;$i<$num;$i++){
            $code = self::randCode($length);
            $array[] = ['course_id'=>$course_id,'code'=>$code];
        }
        return $array;
    }

    /**
     * 生成随机码
     * @param int $len
     * @return false|string
     */
    public static function randCode($length=6){
        return substr(str_shuffle(self::STRING),0,$length);
    }
}
